<template>
  <div class="related" ref="related">
    <div class="page-header">
      <CustomTitle :title="route.meta.title" />
      <el-space>
        <el-input style="max-width: 600px" v-model="paramsForm.searchKeyword" placeholder="请输入关键词" @blur="init">
          <template #prepend>
            <el-select v-model="paramsForm.searchType" style="width: 115px">
              <el-option label="商品标题" :value="1" />
              <el-option label="商品分类" :value="2" />
              <el-option label="品牌" :value="3" />
              <el-option label="商品ID" :value="4" />
            </el-select>
          </template>
        </el-input>
        <el-button type="primary" :icon="RefreshRight" plain @click="resetSearchKey">重置</el-button>
      </el-space>
    </div>
    <div class="fittings-params-form">
      <el-form :model="paramsForm" label-width="auto" ref="paramsRef">
        <el-form-item label="在售价">
          <div class="space">
            <el-input v-model="paramsForm.minPrice" />
            -
            <el-input v-model="paramsForm.maxPrice" />
          </div>
        </el-form-item>
        <el-form-item label="是否特价" prop="isSpecialPrice">
          <el-select v-model="paramsForm.isSpecialPrice">
            <el-option
              v-for="item in paramsOption.bool_type"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品风格" prop="productStyle">
          <el-select v-model="paramsForm.productStyle">
            <el-option
              v-for="item in paramsOption.shop_product_style"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否定制" prop="customType">
          <el-select v-model="paramsForm.customType">
            <el-option
              v-for="item in paramsOption.shop_product_custom_type"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否模型" prop="isModel">
          <el-select v-model="paramsForm.isModel">
            <el-option
              v-for="item in paramsOption.shop_is_model"
              :key="item.dictValue"
              :value="item.dictValue"
              :label="item.dictLabel"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-cascader
            style="width: 100%"
            :options="paramsOption.classify"
            v-model="paramsForm.categoryId"
            :props="{ label: 'name', value: 'categoryId' }"
            :show-all-levels="false"
            clearable
            filterable
          />
        </el-form-item>
      </el-form>
      <div class="fittings-form-btn">
        <el-space>
          <el-button type="primary" :icon="Search" @click="init">查询</el-button>
          <el-button type="primary" :icon="RefreshRight" plain @click="reset">重置</el-button>
        </el-space>
      </div>
    </div>
    <el-checkbox-group v-model="checkedList" class="checkbox-container">
      <el-empty v-if="!data.length && !loading" />
      <div class="loading" v-if="loading && !data.length" v-loading="loading"></div>
      <div class="products-list">
        <div class="products-item" v-for="item in data" :key="item.productId">
          <img ref="imageContainer" :style="{ '--height': imgWidth + 'px' }" @load="getWidth" :src="item.mainPicUrl" alt="" />
          <div class="products-name">{{ item.productName }}</div>
          <div class="checkbox">
            <el-checkbox :value="item.productId" @change="checked(item)"></el-checkbox>
          </div>
        </div>
      </div>
    </el-checkbox-group>
    <div class="pagination">
      <el-pagination
        v-model:current-page="paramsForm.page"
        v-model:page-size="paramsForm.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="init"
        @current-change="init"
      />
    </div>
    <div class="all-checkbox">
      <el-checkbox @change="setCheckAll" v-model="checkAll" :indeterminate="isIndeterminate">全选</el-checkbox>
      <el-space>
        <el-button type="primary" @click="confirm(true)">确认关联</el-button>
        <el-button type="info" text bg v-if="!checkedList.length" @click="confirm(false)">返回</el-button>
        <el-button type="info" text bg v-else @click="cancel">取消</el-button>
      </el-space>
    </div>
    <el-dialog v-model="returnVisible" width="30%" center align-center>
      <div class="sure">
        <div>
          <img src="@/assets/success.png" alt="" />
        </div>
        <span>关联产品添加成功！可前往商品定制模版查看详情~ </span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="returnVisible = false">关闭</el-button>
          <el-button
            type="primary"
            @click="router.push({ path: '/shopConfig/customization/RelatedProducts', query: { ...route.query } })"
          >
            查看详情
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import CustomTitle from "@/components/CustomTitle/index.vue";
import { RefreshRight, Search } from "@element-plus/icons-vue";
import { useElementSize } from "@vueuse/core";
import { selectDictDataByType } from "@/apis/dict/dict";
import { getCategoryTree } from "@/apis/manage";
import router from "@/router";
import { ElMessage } from "element-plus";
import { addRelation, searchProducts } from "@/apis/products/shopConfig";

/**
 * 获取内容区域大小
 */
const related = ref(null);
const { width } = useElementSize(related);

const route = useRoute();
const paramsRef = ref(null);
const checkedList = ref([]);
const paramsForm = ref({
  page: 1,
  size: 10,
  searchType: 1,
  searchKeyword: ""
});
const imageContainer = ref(null);
const imgWidth = ref(0);
const data = ref([]);
const total = ref(0);
const paramsOption = ref({});
const checkAll = ref(false);
const isIndeterminate = ref(false);
const list = ref([]);
const loading = ref(false);
const returnVisible = ref(false);
/**
 * 初始化
 */
const init = async () => {
  const categoryId = paramsForm.value.categoryId ? paramsForm.value.categoryId[paramsForm.value.categoryId.length - 1] : null;
  const res = await searchProducts({
    ...paramsForm.value,
    categoryId,
    isFactoryQa: 1,
    customTemplateId: route.query.customTemplateId
  });
  data.value = res.data.records;
  total.value = res.data.total;
  loading.value = false;
};
/**
 * 根据图片宽度计算图片高度
 */
const getWidth = () => {
  if (imageContainer.value) imgWidth.value = imageContainer.value[0].offsetWidth;
};
/**
 * 选择
 */
const checked = item => {
  checkAll.value = data.value.every(item => checkedList.value.includes(item.productId));
  isIndeterminate.value = !data.value.every(item => checkedList.value.includes(item.productId)) && checkedList.value.length > 0;
};
/**
 * 设置全选
 */
const setCheckAll = () => {
  if (checkAll.value) {
    checkedList.value = [...new Set([...checkedList.value, ...data.value.map(v => v.productId)])];
  } else {
    checkedList.value = list.value.filter(v => !data.value.find(item => item.productId === v.productId)).map(v => v.productId);
  }
  isIndeterminate.value = false;
};
/**
 * 内容区域大小的变化，重新计算图片高度
 */
watch(width, () => {
  getWidth();
});
/**
 * 重置搜索条件
 */
const reset = () => {
  paramsForm.value.maxPrice = undefined;
  paramsForm.value.minPrice = undefined;
  paramsRef.value.resetFields();
  init();
};
/**
 * 获取列表选项字典
 * @param {*} dictType 字典类型
 */
const getDict = async dictType => {
  const res = await selectDictDataByType(dictType);
  paramsOption.value[dictType] = res.data;
};
/**
 *  获取分类
 */
const getClassify = async () => {
  const res = await getCategoryTree();
  paramsOption.value.classify = res.data;
};
const confirm = async isB => {
  if (!isB) return router.back();
  if (isB && !checkedList.value.length) return ElMessage.error("请选择关联商品");
  const res = await addRelation({
    customTemplateId: route.query.customTemplateId,
    productIds: checkedList.value
  });
  if (res.code === 200) {
    returnVisible.value = true;
  }
};
const cancel = () => {
  checkedList.value = [];
  list.value = [];
  checkAll.value = false;
  isIndeterminate.value = false;
};
const resetSearchKey = () => {
  paramsForm.value.searchKeyword = "";
  init();
};
onMounted(() => {
  getClassify();
  const dictArr = ["shop_product_custom_type", "shop_product_style", "bool_type", "shop_is_model", "shop_product_custom_type"];
  dictArr.forEach(item => {
    getDict(item);
  });
  loading.value = true;
  init();
});
</script>

<style lang="scss" scoped>
@import "index";
</style>
